import json
import os
import time
import csv
import uuid
import re
from datetime import datetime, timedelta

import numpy as np
import pandas as pd
import chardet

from show_car_slow_num import ShowCarSlowNum
from show_car_speed import ShowCarSpeed
from show_flow_diff import ShowFlowDiff
from show_pass_rate import ShowPassRate
from show_time_duration import ShowTimeDuration


class Gantry:
    def __init__(self, dir_path):
        self.dir_path = dir_path
        self.ctype_time = None
        self.max_speed = 120
        self.dist = None
        self.time_interval = '5T'
        self.event_dict = {}

    def get_files_containing_substring(self, directory, substring):
        file_name = None
        # 遍历指定目录下的所有文件
        for filename in os.listdir(directory):
            # 构建完整的文件路径
            full_path = os.path.join(directory, filename)
            # 检查是否为文件
            if os.path.isfile(full_path):
                # 检查文件名是否包含指定的子字符串
                if substring in filename:
                    file_name = full_path
        return file_name

    def get_match_data(self, path):
        # 使用 chardet 检测文件编码
        with open(path, 'rb') as f:
            result = chardet.detect(f.read(10000))
        detected_encoding = result['encoding']
        # 使用检测到的编码读取 CSV 文件
        df = pd.read_csv(path, encoding=detected_encoding)
        # 转换为字典
        # a = df.to_dict(orient='records')
        # 转换为numpy数组
        df_np = df.to_numpy()
        # 获取第五列（索引为 4）
        fifth_column = df_np[:, 5]
        # 找出第五列值大于 0 的条件
        mask = (fifth_column >= 0) & (fifth_column < 3)
        # 使用布尔索引选择满足条件的行
        filtered_arr = df_np[mask]
        return filtered_arr

    def get_mean_time(self, df_np):
        total_num = len(df_np)
        ctype_time = {}
        for row in df_np:
            ctype = row[1]
            if ctype not in ctype_time:
                ctype_time[ctype] = {}
                ctype_time[ctype]['list'] = []
            # 解析时间差字符串
            time_diff = row[4]
            parts = time_diff.split('m')
            fen = int(parts[0])  # 分钟数
            miao = int(parts[1].split('s')[0])  # 秒数
            # 计算总秒数
            seconds = fen * 60 + miao
            ctype_time[ctype]['list'].append(seconds)
            if seconds < 0:
                print("time_diff: ", time_diff, row)
        for ctype, data in ctype_time.items():
            total_seconds = data['list']
            total_seconds = np.array(total_seconds)
            data['sum'] = np.sum(total_seconds)
            data['mean'] = np.mean(total_seconds)
            data['max'] = np.max(total_seconds)
            data['min'] = np.min(total_seconds)

        return ctype_time

    def get_range(self, mask, time_list, flag=True):
        final_result = []
        time_range = []
        if len(mask) > 0:
            mask = sorted(mask)
            result = []
            start = mask[0]
            end = start
            for i in range(1, len(mask)):
                if mask[i] - mask[i - 1] <= 2:
                    end = mask[i]
                else:
                    # 如果当前元素与前一个元素相差大于 2，则结束当前区间并开始新区间
                    result.append((start, end))
                    start = mask[i]
                    end = start
            # 添加最后一个区间
            result.append((start, end))
            # 处理单独的点
            for start, end in result:
                if start == end:
                    continue
                    # final_result.append((start-1, start))
                else:
                    if flag:
                        if start != 0:
                            start = start - 1
                        if end != len(time_list) - 1:
                            end = end + 1
                    final_result.append((start, end))
        if len(final_result) > 0:
            for start, end in final_result:
                time_range.append((time_list[start], time_list[end]))
                # print((time_list[start], time_list[end]))
        return time_range

    def flow_down_50(self, mate_all_flow_csv_name):
        # 使用pandas读取CSV文件
        path = os.path.join(self.dir_path, mate_all_flow_csv_name)
        df = pd.read_csv(path, parse_dates=["time"], date_parser=lambda x: pd.to_datetime(x, format='%Y/%m/%d %H:%M:%S'))

        # 将每列转换为列表{time  total_flow  up_flow  down_flow  flow_diff}
        columns_as_lists = {col: df[col].tolist() for col in df.columns}
        up_list = columns_as_lists['up_flow']
        down_list = columns_as_lists['down_flow']
        time_list = columns_as_lists['time']
        # for i in range(10, len(up_list)-10):
        #     if up_list[i] > 50 and up_list[i-1] > 50 and up_list[i-2] > 50:
        #         if up_list[i] - up_list[i+1] > 30 and up_list[i] - up_list[i+2] > 30:
        #             mask.append(i)
        # for i in range(10, len(down_list)-10):
        #     if down_list[i] > 50 and down_list[i-1] > 50 and down_list[i-2] > 50:
        #         if down_list[i] - down_list[i+1] > 30 and down_list[i] - down_list[i+2] > 30:
        #             mask.append(i)
        up_array = np.array(up_list)
        # 创建布尔掩码
        up_mask1 = up_array[10:-10] > 20
        up_mask2 = up_array[9:-11] > 20
        up_mask3 = up_array[8:-12] > 30
        up_mask4 = (up_array[10:-10] - up_array[11:-9]) > 20
        up_mask5 = (up_array[10:-10] - up_array[12:-8]) > 20
        # avg_3 = (up_array[10:-10] + up_array[9:-11] + up_array[8:-12]) / 3.0
        # avg_2 = (up_array[9:-11] + up_array[8:-12]) / 2.0
        # 检查骤降是否超过50%  需要考虑除数为0的情况
        # up_mask6 = (avg_3 - avg_2) / avg_3 > 0.3  # 骤降超过50%
        diff = up_array[10:-10] - up_array[11:-9]
        up_mask6 = np.ones_like(diff, dtype=bool)
        up_mask6[diff <= 0] = False
        safe_division = np.where(up_array[10:-10] != 0, up_array[10:-10], 1.0)
        up_ratio = diff / safe_division
        # 更新掩码，当比率大于0.5时为True，否则为False
        up_mask6 &= (up_ratio > 0.5)
        up_mask = up_mask1 & ((up_mask2 & up_mask3 & up_mask4 & up_mask5) | up_mask6)
        up_indices = np.where(up_mask)[0] + 10  # 索引偏移 10
        # print(up_indices)

        down_array = np.array(down_list)
        down_mask1 = down_array[10:-10] > 20
        down_mask2 = down_array[9:-11] > 20
        down_mask3 = down_array[8:-12] > 30
        down_mask4 = (down_array[10:-10] - down_array[11:-9]) > 20
        down_mask5 = (down_array[10:-10] - down_array[12:-8]) > 20
        # avg_3 = (down_array[10:-10] + down_array[9:-11] + down_array[8:-12]) / 3.0
        # avg_2 = (down_array[9:-11] + down_array[8:-12]) / 2.0
        # # 需要考虑除数为0的情况
        # down_mask6 = (avg_3 - avg_2) / avg_3 > 0.3

        diff = down_array[10:-10] - down_array[11:-9]
        down_mask6 = np.ones_like(diff, dtype=bool)
        down_mask6[diff <= 0] = False
        safe_division = np.where(down_array[10:-10] != 0, down_array[10:-10], 1.0)
        down_ratio = diff / safe_division
        # 更新掩码，当比率大于0.5时为True，否则为False
        down_mask6 &= (down_ratio > 0.5)
        down_mask = down_mask1 & ((down_mask2 & down_mask3 & down_mask4 & down_mask5) | down_mask6)
        down_indices = np.where(down_mask)[0] + 10
        # print(down_indices)

        # 合并两个列表
        combined_list = up_indices.tolist() + down_indices.tolist()
        # 删除相同值
        unique_list = list(set(combined_list))
        # 排序
        sorted_list = sorted(unique_list)
        # 删除相邻值相差在5以内的后者
        i = 0
        while i < len(sorted_list) - 1:
            if sorted_list[i + 1] - sorted_list[i] <= 2:
                del sorted_list[i + 1]
            else:
                i += 1
        new_list = [time_list[i] for i in sorted_list]

        return new_list, columns_as_lists

    def slow_move_20(self, slow_vehicle_csv_name):
        path = os.path.join(self.dir_path, slow_vehicle_csv_name)
        df = pd.read_csv(path, parse_dates=["time"], date_parser=lambda x: pd.to_datetime(x, format='%Y/%m/%d %H:%M:%S'))
        columns_as_lists = {col: df[col].tolist() for col in df.columns}
        time_list = columns_as_lists['time']
        count_list = columns_as_lists['count']
        mask = []
        if len(count_list) > 0:
            for i in range(len(count_list)):
                if count_list[i] > 10:
                    mask.append(i)
        time_range = self.get_range(mask, time_list)
        result = []
        for start, end in time_range:
            start_index = time_list.index(start)
            end_index = time_list.index(end) + 1
            result.append(count_list[start_index:end_index])

        return time_range, result

    def pass_rate_70(self, car_pass_rate_csv_name):
        path = os.path.join(self.dir_path, car_pass_rate_csv_name)
        df = pd.read_csv(path, parse_dates=["Group_Time"], date_parser=lambda x: pd.to_datetime(x, format='%Y/%m/%d %H:%M:%S'))
        columns_as_lists = {col: df[col].tolist() for col in df.columns}
        time_list = columns_as_lists['Group_Time']
        pass_rate_list = columns_as_lists['Percentage']
        total_count_list = columns_as_lists['Total_Count']
        mask = []
        if len(total_count_list) > 0:
            # # 计算小于70的数量所占的比例
            # pass_rate_less_than_70 = sum(1 for x in pass_rate_list if x < 70)
            # total_count = len(pass_rate_list)
            # ratio = pass_rate_less_than_70 / total_count
            # if ratio > 0.6:
            #     for i in range(len(total_count_list)):
            #         if total_count_list[i] < 30 and pass_rate_list[i] < 30:
            #             mask.append(i)
            # else:
            #     for i in range(len(total_count_list)):
            #         if total_count_list[i] > 30 and pass_rate_list[i] < 70:
            #             mask.append(i)
            total_count_less_than_30 = sum(1 for x in total_count_list if x < 30)
            ratio = total_count_less_than_30 / len(pass_rate_list)
            if ratio > 0.7:
                return []
            # 计算小于70的数量所占的比例
            pass_rate_less_than_70 = sum(1 for x in pass_rate_list if x < 70)
            total_count = len(pass_rate_list)
            ratio = pass_rate_less_than_70 / total_count
            if ratio > 0.7:
                return []
            for i in range(len(total_count_list)):
                if total_count_list[i] > 30 and pass_rate_list[i] < 70:
                    mask.append(i)
                # elif total_count_list[i] < 30 and pass_rate_list[i] < 30:
                #     mask.append(i)
        time_range = self.get_range(mask, time_list, flag=False)

        return time_range

    def car_speed_72(self, car_speed_csv_name):
        path = os.path.join(self.dir_path, car_speed_csv_name)
        df = pd.read_csv(path, parse_dates=["transtime_up"], date_parser=lambda x: pd.to_datetime(x, format='%Y/%m/%d %H:%M:%S'))
        columns_as_lists = {col: df[col].tolist() for col in df.columns}
        # transtime_up, duration_seconds, mean_speed, count
        time_list = columns_as_lists['transtime_up']
        duration_seconds_list = columns_as_lists['duration_seconds']
        mean_speed_list = columns_as_lists['mean_speed']
        count_list = columns_as_lists['count']
        mask = []
        if len(mean_speed_list) > 0:
            mean_speed_less_than_72 = sum(1 for x in mean_speed_list if x < (self.max_speed / 3.6 * 0.6))
            ratio = mean_speed_less_than_72 / len(mean_speed_list)
            if ratio > 0.7:
                return [], columns_as_lists
            for i in range(len(mean_speed_list)):
                if mean_speed_list[i] <= (self.max_speed / 3.6 * 0.6) and count_list[i] > 0:
                    mask.append(i)
        # ratio = len(mask) / len(mean_speed_list)
        # if ratio > 0.8:
        #     return []
        time_range = self.get_range(mask, time_list)

        return time_range, columns_as_lists

    def abnormal_flow_0(self, flow_columns_as_lists):
        up_flow = flow_columns_as_lists['up_flow'][10:-10]
        down_flow = flow_columns_as_lists['down_flow'][10:-10]
        time_list = flow_columns_as_lists['time'][10:-10]
        up_array = np.array(up_flow)
        down_array = np.array(down_flow)
        # 创建一个滑动窗口来检测连续6个0
        window_size = 6
        up_zero_mask = (up_array == 0).astype(int)  # 将0转换为1，非0转换为0
        down_zero_mask = (down_array == 0).astype(int)
        up_convolved = np.convolve(up_zero_mask, np.ones(window_size, dtype=int), mode='valid')
        down_convolved = np.convolve(down_zero_mask, np.ones(window_size, dtype=int), mode='valid')
        # 找到所有卷积结果等于5的位置（即连续5个0的起始位置）
        up_start_indices = np.where(up_convolved == window_size)[0]
        down_start_indices = np.where(down_convolved == window_size)[0]
        for i in range(len(up_start_indices)):
            if up_start_indices[i-1] - up_start_indices[i] < 10:
                break
        # 生成新的值
        new_up_values, new_down_values = [], []
        for value in up_start_indices.tolist():
            for offset in range(0, 6):  # 加1, 加2, 加3, 加4, 加5
                new_up_values.append(value + offset)
        for value in down_start_indices.tolist():
            for offset in range(0, 6):  # 加1, 加2, 加3, 加4, 加5
                new_down_values.append(value + offset)
        # 合并并去重
        mask = list(set(new_up_values + new_down_values))
        if len(mask) == 0:
            return []
        time_range = self.get_range(mask, time_list)

        return time_range

    def merged_time_range(self, time_range_list):
        # 合并所有时间区间
        all_intervals = []
        for k in range(len(time_range_list)):
            all_intervals += time_range_list[k]
        # 按起始时间排序
        all_intervals.sort(key=lambda x: x[0])
        if len(all_intervals) == 0:
            return []
        # 合并重叠的时间区间
        merged_intervals = []
        current_start, current_end = all_intervals[0]
        for start, end in all_intervals[1:]:
            # 若相差10分钟，则合并为一个区间
            if (start - timedelta(minutes=10)) <= current_end:
                # 如果当前区间的开始时间在当前结束时间之前或等于当前结束时间，则合并区间
                current_end = max(current_end, end)
            else:
                # 否则，添加当前区间到结果列表，并更新当前区间
                merged_intervals.append((current_start, current_end))
                current_start, current_end = start, end
        # 添加最后一个区间
        merged_intervals.append((current_start, current_end))
        return merged_intervals

    def get_flow_time_range(self, merged_intervals, mate_all_flow_list):
        # 区间中是否包含A内时间
        new_merged_intervals = []
        for i in range(len(merged_intervals)):
            for t in mate_all_flow_list:
                if merged_intervals[i][0] <= t <= merged_intervals[i][1]:
                    new_merged_intervals.append(merged_intervals[i])
                    break
                elif merged_intervals[i][0] - timedelta(minutes=10) <= t < merged_intervals[i][0]:
                    new_merged_intervals.append(
                        (merged_intervals[i][0] - timedelta(minutes=10), merged_intervals[i][1]))
                    break
                elif merged_intervals[i][1] + timedelta(minutes=10) >= t > merged_intervals[i][1]:
                    new_merged_intervals.append(
                        (merged_intervals[i][0], merged_intervals[i][1] + timedelta(minutes=10)))
                    break
        return new_merged_intervals

    def deal_time(self, mate_all_flow_list, slow_vehicle_list, car_pass_rate_list, car_speed_list, abnormal_flow_list):
        # new_mate_all_flow_list = []
        # for i in range(len(mate_all_flow_list)):
        #     new_mate_all_flow_list.append((mate_all_flow_list[i], mate_all_flow_list[i]+timedelta(minutes=10)))

        merged_intervals = self.merged_time_range([car_pass_rate_list, car_speed_list])
        new_merged_intervals = self.get_flow_time_range(merged_intervals, mate_all_flow_list)

        all_list = [slow_vehicle_list, new_merged_intervals, abnormal_flow_list]
        new_merged = self.merged_time_range(all_list)

        # new_merged = []
        # if len(new_merged_intervals) > 0:
        #     new_merged.append(new_merged_intervals[0])
        #     for i in range(1, len(new_merged_intervals)):
        #         if new_merged_intervals[i][0] > new_merged_intervals[i-1][1]:
        #             new_merged.append(new_merged_intervals[i])
        #         else:
        #             new_merged[-1] = (new_merged[-1][0], max(new_merged[-1][1], new_merged_intervals[i][1]))

        # 输出结果
        # print("合并后的时间区间:", merged_intervals)
        print("合并后且包含流量突变的时间区间:", new_merged)
        return new_merged

    def get_flow_speed(self, time_list, flow_columns_as_lists, speed_columns_as_lists):
        flow_speed_dict = {}
        if len(time_list) > 0:
            for i in range(len(time_list)):
                new_dict = {}
                for k, x in enumerate(flow_columns_as_lists['time']):
                    if x == time_list[i]:
                        new_dict['up_flow'] = flow_columns_as_lists['up_flow'][k]
                        new_dict['down_flow'] = flow_columns_as_lists['down_flow'][k]
                        break
                for k, x in enumerate(speed_columns_as_lists['transtime_up']):
                    if x == time_list[i]:
                        new_dict['mean_speed'] = speed_columns_as_lists['mean_speed'][k]
                        break
                flow_speed_dict[time_list[i]] = new_dict

        return flow_speed_dict

    def get_event_dict(self, merged_intervals, flow_speed_dict, abnormal_flow_list, slow_vehicle_list, slow_vehicle_count_lists):
        self.event_dict['event_num'] = len(merged_intervals)
        self.event_dict['event'] = []
        if len(merged_intervals) == 0:
            return
        for i in range(len(merged_intervals)):
            new_dict = {}
            start = merged_intervals[i][0]
            end = merged_intervals[i][1]
            duration = end - start
            new_dict['start'] = start.strftime('%Y-%m-%d %H:%M:%S')
            new_dict['end'] = end.strftime('%Y-%m-%d %H:%M:%S')
            new_dict['duration(min)'] = int(duration.total_seconds() / 60)

            slow_level = 0
            for k in range(len(slow_vehicle_list)):
                if start <= slow_vehicle_list[k][0] <= end:
                    # 慢行时间
                    t = int((slow_vehicle_list[k][1]-slow_vehicle_list[k][0]).total_seconds() / 60)
                    t_level = (1 if t <= 30 else 2 if 30 < t <= 90 else 3)
                    # 慢行峰值
                    max_vehicles = max(slow_vehicle_count_lists[k])
                    max_level = (1 if max_vehicles <= 30 else 2 if 30 < max_vehicles <= 60 else 3)
                    # 慢行总数
                    sum_vehicles = sum(slow_vehicle_count_lists[k])
                    sum_level = (1 if sum_vehicles <= 60 else 2 if 60 < sum_vehicles <= 150 else 3)
                    # 慢行数量差值
                    diff = [slow_vehicle_count_lists[k][i + 1] - slow_vehicle_count_lists[k][i] for i in range(len(slow_vehicle_count_lists[k]) - 1)]
                    max_diff = max(diff)

                    slow_level_k = 0.25 * t_level + 0.5 * max_level + 0.25 * sum_level
                    slow_level = max(slow_level, slow_level_k)

            time_level = (1 if duration <= timedelta(minutes=30) else 2 if timedelta(minutes=30) < duration <= timedelta(minutes=90) else 3)

            if slow_level >= 2:
                new_dict['level'] = int(max(slow_level, time_level))
            else:
                new_dict['level'] = int(time_level)

            for k in range(len(abnormal_flow_list)):
                if start <= abnormal_flow_list[k][0] <= end:
                    new_dict['level'] = int(3)
            new_dict['up_flow'] = flow_speed_dict[start]['up_flow']
            new_dict['down_flow'] = flow_speed_dict[start]['down_flow']
            new_dict['mean_speed'] = flow_speed_dict[start]['mean_speed']
            self.event_dict['event'].append(new_dict)

    def save_event_dict(self, csv_name):
        path = os.path.join(self.dir_path, csv_name)
        # 提取事件数据
        events = self.event_dict['event']
        event_list = []
        if events:
            for i in range(len(events)):
                event = events[i]
                event_data = {
                    'gantry_up': self.event_dict['gantry_up'],
                    'gantry_down': self.event_dict['gantry_down'],
                    'year': self.event_dict['year'],
                    'month': self.event_dict['month'],
                    'day': self.event_dict['day'],
                    'dist': self.event_dict['dist'],
                    'event_num': self.event_dict['event_num'],
                    'start': event['start'],
                    'end': event['end'],
                    'duration(min)': event['duration(min)'],
                    'level': event['level'],
                    'up_flow': event['up_flow'],
                    'down_flow': event['down_flow'],
                    'mean_speed': event['mean_speed']
                }
                event_list.append(event_data)
        else:
            # 如果 event 为空，创建一个包含默认值的字典
            default_event = {
                'gantry_up': self.event_dict['gantry_up'],
                'gantry_down': self.event_dict['gantry_down'],
                'year': self.event_dict['year'],
                'month': self.event_dict['month'],
                'day': self.event_dict['day'],
                'dist': self.event_dict['dist'],
                'event_num': self.event_dict['event_num'],
                'start': pd.NaT,
                'end': pd.NaT,
                'duration(min)': None,
                'level': None,
                'up_flow': None,
                'down_flow': None,
                'mean_speed': None
            }
            event_list.append(default_event)

        df = pd.DataFrame(event_list)
        columns_order = ['gantry_up', 'gantry_down', 'year', 'month', 'day', 'dist', 'event_num', 'level', 'start', 'end',  'duration(min)', 'up_flow', 'down_flow', 'mean_speed']
        df = df[columns_order]
        df.to_csv(path, index=False, encoding='utf-8')

    def run(self):
        up_path = self.get_files_containing_substring(self.dir_path, 'up_G')
        down_path = self.get_files_containing_substring(self.dir_path, 'down_G')
        all_path = self.get_files_containing_substring(self.dir_path, 'all_G')
        gantry_id = os.path.basename(up_path).split('_')[1]
        # self.event_dict['gantry_up'] = gantry_id.split('-')[0].split(',')[0]
        # self.event_dict['gantry_down'] = gantry_id.split('-')[0].split(',')[1]
        # self.event_dict['year'] = gantry_id.split('-')[1][:4]
        # self.event_dict['month'] = gantry_id.split('-')[1][4:6]
        # self.event_dict['day'] = gantry_id.split('-')[1][6:8]

        self.event_dict['gantry_up'] = gantry_id.split('-')[0]
        self.event_dict['gantry_down'] = gantry_id.split('-')[1]
        self.event_dict['year'] = gantry_id.split('-')[2]
        self.event_dict['month'] = gantry_id.split('-')[3]
        self.event_dict['day'] = gantry_id.split('-')[4]
        self.event_dict['source'] = gantry_id.split('-')[5][:2]

        # 获取合并后数据的numpy数组 （0/1/2）无异常值
        df_np = self.get_match_data(all_path)
        # 计算总间隔时长，平均间隔时长， 最大间隔时长，最小间隔时长
        self.ctype_time = self.get_mean_time(df_np)
        # print("最小间隔时长: ", ctype_time)
        m = list(self.ctype_time.keys())

        if 1 in self.ctype_time:
            seconds_min = self.ctype_time[1]['min']
            seconds_average = self.ctype_time[1]['mean']
        else:
            return False

        if seconds_min <= 10:
            return False

        # 估算区间距离(米)
        self.dist = round(self.max_speed / 3.6 * seconds_min, 2)
        print(self.event_dict)
        self.event_dict['dist'] = int(self.dist)

        car_speed_csv_name = "car_time_data.csv"
        type_time_csv_name = "time_duration_data.csv"
        slow_vehicle_csv_name = "car_slow_move_data.csv"
        mate_all_flow_csv_name = "mate_flow_data.csv"
        car_pass_rate_csv_name = "car_pass_rate_data.csv"
        all_pass_rate_csv_name = "all_pass_rate_data.csv"
        abnormal_data_csv_name = 'abnormal_data.csv'

        # 上下游门架的流量骤变的时间节点
        mate_all_flow_list, flow_columns_as_lists = self.flow_down_50(mate_all_flow_csv_name)
        print("流量骤变:", mate_all_flow_list)
        # 慢行车辆数量大于20的时间区间
        slow_vehicle_list, slow_vehicle_count_lists = self.slow_move_20(slow_vehicle_csv_name)
        print("慢行车辆:", slow_vehicle_list)
        # 客车车辆通过率低于70%的时间区间
        # car_pass_rate_list = self.pass_rate_70(car_pass_rate_csv_name)
        # print("客车车辆通过率:", car_pass_rate_list)
        # 所有车型车辆通过率低于70%的时间区间
        all_pass_rate_list = self.pass_rate_70(all_pass_rate_csv_name)
        print("所有车型车辆通过率:", all_pass_rate_list)
        # 客车平均速度低于20m/s的时间区间
        car_speed_list, speed_columns_as_lists = self.car_speed_72(car_speed_csv_name)
        print("客车平均速度:", car_speed_list)

        abnormal_flow_list = self.abnormal_flow_0(flow_columns_as_lists)
        print("流量阻断情况:", abnormal_flow_list)

        merged_intervals = self.deal_time(mate_all_flow_list, slow_vehicle_list, all_pass_rate_list, car_speed_list, abnormal_flow_list)
        time_list = []
        for i in range(len(merged_intervals)):
            time_list.append(merged_intervals[i][0])
        flow_speed_dict = self.get_flow_speed(time_list, flow_columns_as_lists, speed_columns_as_lists)

        self.get_event_dict(merged_intervals, flow_speed_dict, abnormal_flow_list, slow_vehicle_list, slow_vehicle_count_lists)
        # print(self.event_dict)

        # 保存事件数据
        csv_name = 'event_' + gantry_id + '.csv'
        # self.save_event_dict(csv_name)

        showCarSpeed = ShowCarSpeed()
        showCarSpeed.read_file1(os.path.join(self.dir_path, car_speed_csv_name), self.event_dict['event'])
        showTimeDuration = ShowTimeDuration()
        showTimeDuration.read_file1(os.path.join(self.dir_path, type_time_csv_name), self.event_dict['event'])
        showCarSlowNum = ShowCarSlowNum()
        showCarSlowNum.read_file1(os.path.join(self.dir_path, slow_vehicle_csv_name), self.event_dict['event'])
        showFlowDiff = ShowFlowDiff()
        showFlowDiff.read_file1(os.path.join(self.dir_path, mate_all_flow_csv_name), self.event_dict['event'])
        showPassRate = ShowPassRate()
        showPassRate.read_file1(os.path.join(self.dir_path, car_pass_rate_csv_name), self.event_dict['event'])
        showPassRate.read_file1(os.path.join(self.dir_path, all_pass_rate_csv_name), self.event_dict['event'])

        event = self.event_dict.copy()
        self.clear()
        return event

    def clear(self):
        self.ctype_time = None
        self.dist = None
        self.event_dict.clear()


def save_all_event_dict(data, path):
    for i in range(len(data)):
        data[i]['event'] = str(data[i]['event'])
    fieldnames = ['gantry_up', 'gantry_down', 'year', 'month', 'day', 'source', 'dist', 'event_num', 'event']

    parts = path.split('\\')  # 将路径按反斜杠分割
    for part in parts:
        if '邻垫高速' in part:
            for i in range(len(data)):
                data[i]['source'] = '流水'

    with open(path, mode='w', newline='', encoding='utf-8') as file:
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        writer.writeheader()
        rows = []
        for i in range(len(data)):
            # 使用字典来构造每一行
            row_dict = {
                'gantry_up': data[i]['gantry_up'],
                'gantry_down': data[i]['gantry_down'],
                'year': data[i]['year'],
                'month': data[i]['month'],
                'day': data[i]['day'],
                'source': data[i]['source'],
                'dist': data[i]['dist'],
                'event_num': data[i]['event_num'],
                'event': data[i]['event']
            }
            rows.append(row_dict)

        writer.writerows(rows)


if __name__ == '__main__':
    # all_event = []
    # dir_path = r'D:\GJ\项目\事故检测\output\纳黔高速\G007651003000510010-G007651003000410010-2024-06-12-流水'
    # gantry = Gantry(dir_path)
    # data = gantry.run()
    # if data['event']:
    #     all_event.append(data)
    # if all_event:
    #     save_all_event_dict(all_event, r'D:\GJ\项目\事故检测\output\邻垫高速\event.csv')

    all_event = []
    ii = 0
    last_time = time.time()
    top_dir = r'D:\GJ\项目\事故检测\output\纳黔高速'
    # 使用 os.walk 遍历文件夹
    for root, dirs, files in os.walk(top_dir):
        # root 是当前正在遍历的这个文件夹的本身的路径
        # dirs 是一个 list，内容是该文件夹中所有的目录的名字(不包括子目录)
        # files 同样是 list, 内容是该文件夹中所有的文件(不包括子目录)
        # 输出当前遍历到的文件夹路径
        # print(f"Folder: {root}")
        # 输出该文件夹下的所有子文件夹
        for dir_name in dirs:
            dir_path = os.path.join(root, dir_name)
            print(f"  Directory: {os.path.join(root, dir_name)}")
            gantry = Gantry(dir_path)
            data = gantry.run()
            if data:
                all_event.append(data)
            now_time = time.time()
            T = now_time - last_time
            last_time = now_time
            ii += 1
            print(ii, T)

        break   # 不遍历深层次的文件目录
    save_all_event_dict(all_event, r'D:\GJ\项目\事故检测\output\纳黔高速\event.csv')
